package com.markyao.controller;

import com.markyao.dao.pojo.User;
import com.markyao.service.UserService;
import com.markyao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    UserService userService;

    @PostMapping
    public Result updateAvater(@RequestPart("avatar")MultipartFile multipartFile, HttpSession session){
        User user = (User) session.getAttribute("user");
        //原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机生成一个文件名
        String prefixx = UUID.randomUUID().toString();
        //拼接成唯一的文件名
        String fileName=prefixx+suffix;
//        String parent = session.getServletContext().getRealPath("upload");//找到upload文件夹子所在位置

//        String parent="E:\\develop\\workspace\\store\\store_app\\src\\main\\resources\\static\\upload";
        String parent=session.getServletContext().getRealPath("upload");
        File dir=new File(parent);//在upload文件夹位置创建一个文件夹
        if(!dir.exists()){
            dir.mkdirs();//创建目录
        }
        File dest=new File(dir,fileName);//创建upload目录下一个空文件-->xxxxx.jpg
        try {
            multipartFile.transferTo(dest);//将文件中的数据写入dest空文件中
        } catch (IOException e) {
            e.printStackTrace();
        }
        user.setAvatar("/upload/"+fileName);
        return userService.updateAvater(user);
    }
}
